# include "serialib.h"
# include "socat_manager.h"
# include "serial_logger.h"

int main(int argc, char* argv[]) {
    char buffer[1024];
    int bytesRead;

    // 默认配置
    unsigned int baudRate = 115200;
    std::string physicalPort = "/dev/ttyUSB0";
    std::string virtualTx = "/tmp/virtual_tx";
    std::string virtualRx = "/tmp/virtual_rx";
    std::string logFile = "serial_log_" + 
        std::to_string(std::time(nullptr)) + ".txt";
    
    // 解析命令行参数
    if (argc < 5) {
        std::cerr << "用法: " << argv[0] << " [波特率] [物理端口名称] [日志文件] [虚拟端口名称]" << std::endl;
        return 1;
    }

    try 
    {
        baudRate = std::stoi(argv[1]);
    } 
    catch (...) 
    {
        std::cerr << "无效的波特率，使用默认值: " << baudRate << std::endl;
    }
    physicalPort = argv[2];
    logFile = argv[3];
    std::string virtualPort = argv[4];
    virtualTx = virtualPort + "_tx";
    virtualRx = virtualPort;
    
    // 注册信号处理函数
    signal(SIGINT, signalHandler);
    signal(SIGTERM, signalHandler);
    
    serial_logger m_logger(baudRate, physicalPort, virtualTx, virtualRx, logFile);

    std::thread p([&]() -> void {
        std::cout << "开始转发二进制数据（日志中以十六进制记录），按Ctrl+C停止" << std::endl;
        
        m_logger.run();
    });

    while (running)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    m_logger.stop();

    p.join();
    
    std::cout << "程序已退出" << std::endl;

    return 0;
}
    
